import React, { useEffect, useState } from 'react';
import { Button, Space, Table, Modal, Form, Input, Select, TreeSelect, InputNumber, message } from 'antd';
import type { TableColumnsType } from 'antd';
import { 
  getTreeTableData, 
  addTreeTable, 
  deleteTreeTableData,
  updateTreeTableData 
} from '@/api/modules/treeTable';
import * as Icons from '@ant-design/icons';
import { nanoid } from 'nanoid';
import dayjs from 'dayjs'
const { confirm } = Modal;

// 修改后的 DataType 接口
interface DataType {
  key: React.ReactNode;
  name?: string;
  age?: number;
  address?: string;
  title?: string;
  path?: string;
  icon?: string;
  order?: number;
  createTime?: string;
  action?: string;
  children?: DataType[];
  id?: number;
  parentId?: number;
}

// 定义表单数据类型
interface FormValues {
  name: string;
  path: string;
  icon: string;
  order: number;
  parentId?: number;
}

const UserList: React.FC = () => {
  const [treeTableData, setTreeTableData] = useState<DataType[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);
  const [modalType, setModalType] = useState<'add' | 'edit'>('add');
  const [currentRecord, setCurrentRecord] = useState<DataType | null>(null);
  const [form] = Form.useForm();
  
  // 获取所有图标名称
  const iconOptions = Object.keys(Icons)
    .map(iconName => ({
      label: iconName,
      value: iconName,
      icon: React.createElement(Icons[iconName as keyof typeof Icons])
    }));

  // 表头
  const columns: TableColumnsType<DataType> = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
      render: (_, record) => {
        const Icon = Icons[record.icon as keyof typeof Icons];
        return Icon ? <Icon /> : record.icon || '';
      }
    },
    {
      title: '排序',
      dataIndex: 'order',
      key: 'order',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, record) => (
        <Space>
          <a onClick={() => showModal('edit', record)}>更新</a>
          <a onClick={() => handleDelete(record)}>删除</a>
        </Space>
      ),
    }
  ];

  // 获取所有行的key值用于默认展开
  const getAllRowKeys = (data: DataType[]): React.Key[] => {
    let keys: React.Key[] = [];
    data.forEach(item => {
      if (item.key) {
        keys.push(item.key);
      }
      if (item.children && item.children.length > 0) {
        keys = keys.concat(getAllRowKeys(item.children));
      }
    });
    return keys;
  };

  // 扁平数据(一维数组)转树形结构函数 - 优化版本
  const buildTree = (data: DataType[]): DataType[] => {
    // 创建数据映射，不修改原始数据
    const dataMap: Record<string | number, DataType> = {};
    data.forEach(item => {
      // 只复制必要的属性，不包含children
      dataMap[item.id!] = {
        ...item,
        key: item.id
      };
    });

    const tree: DataType[] = [];
    data.forEach(item => {
      if (item.parentId) {
        // 如果有父级ID，则添加到父级的children中
        const parent = dataMap[item.parentId];
        if (parent) {
          if (!parent.children) {
            parent.children = [];
          }
          parent.children.push(dataMap[item.id!]);
        }
      } else {
        // 如果没有父级ID，则为根节点
        tree.push(dataMap[item.id!]);
      }
    });

    return tree;
  };

  // 获取树形结构的表数据
  const getTaleList = async () => {
    let res = await getTreeTableData()
    if (res?.status === 200) {
      // 在构建树形结构前清理数据
      const cleanData = res?.data?.data.map((item: DataType) => {
        // 确保一级菜单不包含children属性
        if (!item.parentId || item.parentId === 0) {
          const { children, ...cleanItem } = item;
          return cleanItem;
        }
        return item;
      });
      
      const treeData = buildTree(cleanData);
      setTreeTableData(treeData);
      // 设置默认展开所有行
      setExpandedRowKeys(getAllRowKeys(treeData));
    }
  }

  useEffect(() => {
    getTaleList()
  }, [])

  // 显示模态框
  const showModal = (type: 'add' | 'edit' = 'add', record?: DataType) => {
    setModalType(type);
    if (type === 'edit' && record) {
      setCurrentRecord(record);
      form.setFieldsValue({
        name: record.name,
        path: record.path,
        icon: record.icon,
        order: record.order,
        parentId: record.parentId || 0
      });
    } else {
      form.setFieldsValue({
        order: 0,
        parentId: 0
      });
      setCurrentRecord(null);
    }
    setIsModalVisible(true);
  };

  // 处理模态框确认
  const handleOk = () => {
    form.validateFields().then(async (values: FormValues) => {
      try {
        if (modalType === 'add') {
          // 新增逻辑
          const newData = {
            ...values,
            id: nanoid(),
            createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
          };
          let res = await addTreeTable(newData);
          if (res?.status === 200) {
            message.success('新增成功');
          } else {
            message.error('新增失败');
          }
        } else {
          // 编辑逻辑 - 优化部分
          if (currentRecord) {
            const updateData = {
              ...currentRecord,
              ...values,
            };
            
            // 关键优化：确保一级菜单不包含children属性
            if (!updateData.parentId || updateData.parentId === 0) {
              delete updateData.children;
            }
            
            // 调用更新API
            let res = await updateTreeTableData(currentRecord.id!, updateData);
            if (res?.status === 200) {
              message.success('更新成功');
            } else {
              message.error('更新失败');
            }
          }
        }
        
        setIsModalVisible(false); // 关闭模态框
        form.resetFields(); // 重置表单
        setCurrentRecord(null); // 当前记录设为null
        getTaleList(); // 重新获取数据
      } catch (error) {
        message.error(modalType === 'add' ? '新增失败' : '更新失败');
      }
    }).catch(info => {
      console.log('验证失败:', info);
    });
  };

  // 处理模态框取消
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
    setCurrentRecord(null);
  };

  // 添加删除功能函数
  const handleDelete = (record: DataType) => {
    // 检查是否有子级菜单
    if (record.children && record.children.length > 0) {
      message.warning('该菜单下有子级菜单，不能直接删除！');
      return;
    }

    confirm({
      title: '确认删除',
      content: `确定要删除菜单"${record.name}"吗？此操作不可恢复。`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          await deleteTreeTableData(record.id);
          message.success('删除成功');
          getTaleList();
        } catch (error) {
          message.error('删除失败');
        }
      },
      onCancel() {
        console.log('取消删除');
      },
    });
  };

  // 处理展开状态改变
  const handleExpandedRowsChange = (expandedKeys: readonly React.Key[]) => {
    setExpandedRowKeys([...expandedKeys]);
  };

  // 转换树形数据以适配 TreeSelect
  const convertToTreeData = (data: DataType[]): any[] => {
    return data.map(item => ({
      title: item.name,
      value: item.id,
      children: item.children ? convertToTreeData(item.children) : undefined
    }));
  };

  const treeData = [
    {
      title: '根目录',
      value: 0,
      children: convertToTreeData(treeTableData)
    }
  ];

  return (
    <>
      <Space>
        <Button type='primary' onClick={() => showModal('add')}>新增</Button>
      </Space>
      <Table<DataType>
        columns={columns}
        dataSource={treeTableData}
        expandable={{
          expandedRowKeys: expandedRowKeys,
          onExpandedRowsChange: handleExpandedRowsChange,
        }}
      />

      <Modal
        title={modalType === 'add' ? "新增菜单" : "编辑菜单"}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="菜单名称"
            rules={[{ required: true, message: '请输入菜单名称!' }]}
          >
            <Input placeholder="请输入菜单名称" />
          </Form.Item>

          <Form.Item
            name="path"
            label="路径"
            rules={[{ required: true, message: '请输入路径!' }]}
          >
            <Input placeholder="请输入路径" />
          </Form.Item>

          <Form.Item
            name="icon"
            label="图标"
            rules={[{ required: true, message: '请选择图标!' }]}
          >
            <Select
              placeholder="请选择图标"
              optionFilterProp="label"
              options={[
                { value: 'RightOutlined', label: '右箭头' },
                { value: 'DownOutlined', label: '下箭头' },
                { value: 'UpOutlined', label: '上箭头' },
                { value: 'LeftOutlined', label: '左箭头'},
              ]}
            />
          </Form.Item>

          <Form.Item
            name="order"
            label="排序"
          >
            <InputNumber min={0} />
          </Form.Item>

          <Form.Item
            name="parentId"
            label="父级菜单"
          >
            <TreeSelect
              treeData={treeData}
              treeDefaultExpandAll
              placeholder="请选择父级菜单"
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default UserList;